//
//  LocalizationManager.swift
//  CommonTools
//
//  Created by xianquan on 2024/9/25.
//

import Foundation

public enum XWLanguage: String, CaseIterable {
    case cn = "zh-Hans"
    case cntw = "zh-Hant"
    case en
    case ar
    case bg
    case de
    case el
    case es
    case fr
    case `in`
    case it
    case he
    case ja
    case ko
    case nl
    case pl
    case pt
    case ro
    case ru
    case sv
    case th
    case tr
    case uk
    case vi
    
    public var showName: String {
        ""
    }
    
    fileprivate var tableName: String {
        switch self {
        case .cn:
            return "Localizable_chinese_simplified"
        case .cntw:
            return "Localizable_chinese_traditional"
        case .en:
            return "Localizable_english"
        case .he:
            return "Localizable_iw"
        default:
            return "Localizable_\(rawValue)"
        }
    }
}


public class LocalizationManager {
    
    static let langKey = "JCameraLanguage"
    
    fileprivate static var systemLanguage: String {
        let languages = NSLocale.preferredLanguages
        return languages.first ?? ""
    }
    
    fileprivate static var bundle = Bundle(bundleName: "Localization", podName: "") ?? Bundle.main
    
    public static var currentLanguage: XWLanguage = LocalizationManager.getCurrentLanguage

    public static var getCurrentLanguage: XWLanguage {
//        let langStr = UserDefaults.standard.string(forKey: langKey) ?? ""
//        if let lang = XWLanguage(rawValue: langStr) {
//            return lang
//        }
        let str = LocalizationManager.systemLanguage
        for lang in XWLanguage.allCases {
            if str.hasPrefix(lang.rawValue) {
                return lang
            }
        }
        return .en
    }
    
    public static func setCurrentLanguage(_ language: XWLanguage) {
        UserDefaults.standard.setValue(language.rawValue, forKey: langKey)
        UserDefaults.standard.synchronize()
        LocalizationManager.currentLanguage = language
        XWClassRoomManager.shared.refreshAllAfterChangeLanguage()
    }
}


public extension String {
    var localize: Self {
        let str = NSLocalizedString(self, tableName: LocalizationManager.currentLanguage.tableName, bundle: LocalizationManager.bundle, comment: "")
        return str
    }
    
    
}
